<!--
 * @Author: xuwejie 1529315455@qq.com
 * @Date: 2023-08-28 14:39:14
 * @LastEditors: xuwejie 1529315455@qq.com
 * @LastEditTime: 2023-12-02 10:46:54
 * @FilePath: \v9\src\views\financial\financialOther.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <div class="main_spac1" style="padding-bottom: 0">
      <div class="main_white main_ti" style="width: 100%; padding: 0 10px">
        <el-tabs
          v-model="form.account_status"
          @tab-click="getArticleList"
          class="box"
          style="width: 100%"
        >
          <el-tab-pane
            v-for="(v, k) in account_status_list"
            :label="v"
            :name="k + ''"
            :key="k"
          />
        </el-tabs>
      </div>
    </div>
    <MainPage style="padding-top: 0">
      <template v-slot:HeaderLeft>
        <div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="配送日期：" prop="sendTime">
              <el-date-picker
                v-model="sendTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="dateOption"
                @change="getArticleList"
              />
            </el-form-item>
            <el-form-item label="订单：" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="订单"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户：" prop="uid">
              <change-user-input
                ref="changeUserInput"
                @sendValue="getUser"
                @clear="clearUid"
                @change="getArticleList"
              ></change-user-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
            </MainFormBtn>
            <div class="more el-form-item" @click="moredata = !moredata">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <div>
                  <el-form-item label="下单日期：" prop="createTime">
                    <el-date-picker
                      v-model="createTime"
                      type="daterange"
                      class="time220"
                      :editable="false"
                      unlink-panels
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      :clearable="false"
                      :picker-options="dateOption"
                      @change="getArticleList"
                    />
                  </el-form-item>
                  <el-form-item label="收货信息：" prop="contact">
                    <el-input
                      v-model.trim="form.contact"
                      placeholder="收货人/收货手机"
                      clearable
                      class="wid220"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="业务员：" prop="salesman_id">
                    <el-select
                      v-model.trim="form.salesman_id"
                      placeholder="单据类型"
                      class="wid220"
                      @change="getArticleList"
                    >
                      <el-option label="所有" value=""></el-option>
                      <el-option
                        v-for="(item, index) in salesman"
                        :key="index"
                        :label="item"
                        :value="index"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <div class="clearfix"></div>
                  <el-form-item label=" ">
                    <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    </MainFormBtn>
                  </el-form-item>
                  <!-- <el-form-item label="对账状态" prop="account_status">
                  <el-select
                    v-model.trim="form.account_status"
                    placeholder="对账状态"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(item, index) in account_status_list"
                      :key="index"
                      :label="item"
                      :value="index + 1"
                    ></el-option>
                  </el-select>
                </el-form-item> -->
                </div>
              </div>
            </el-collapse-transition>
          </el-form>
          <div class="main-controls-wrap mg-t-4">
            <div>
              <router-link
                v-if="form.account_status == 1"
                style="margin-right: 10px"
                to="/financial/other/addOrder"
                class="mainor_tea"
                >创建虚单</router-link
              >
              <router-link
                :to="'/financial/other/user?status=' + form.account_status"
                class="mainor_tea mg-r-6"
                >目标用户</router-link
              >
              <el-button @click="pldeliver"
                >批量打印
                <el-tooltip effect="dark" placement="bottom">
                  <div slot="content">
                    注释：打印机纸张需要后进纸，连续打印没有预览效果
                  </div>
                  <svg
                    aria-hidden="true"
                    class="new_navbar_svg"
                    width="14"
                    height="14"
                  >
                    <use xlink:href="#icon-summary_question" />
                  </svg> </el-tooltip
              ></el-button>
              <el-button @click="batchexport" :loading="exportLoading">批量导出</el-button>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:Table>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
          @row-dblclick="rowDblclick"
        >
          <el-table-column width="60" type="selection" />
          <el-table-column
            label="订单号"
            prop="order_sn"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="用户名称" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{
                scope.row.nickname ||
                (scope.row.member && scope.row.member.nickname)
              }}
            </template>
          </el-table-column>
          <el-table-column label="下单日期" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ parseTime(scope.row.created_at, "{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column label="配送日期" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ parseTime(scope.row.send_time, "{y}-{m}-{d}") }}
            </template></el-table-column
          >
          <el-table-column
            label="原下单金额"
            prop="should_money"
            :show-overflow-tooltip="true"
            v-if="show_original_order_data"
          >
            <template slot-scope="scope">
              {{
                form.account_status == 0
                  ? scope.row.should_money
                  : scope.row.original_should_money
              }}
            </template>
          </el-table-column>

          <el-table-column
            label="下单金额"
            prop="nickname"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.order_empty
                  ? scope.row.order_empty.should_money
                  : scope.row.should_money
              }}
            </template>
          </el-table-column>

          <el-table-column
            label="原配送金额"
            prop="send_money"
            :show-overflow-tooltip="true"
            v-if="show_original_order_data"
          >
            <template slot-scope="scope">
              {{
                form.account_status == 0
                  ? scope.row.send_money
                  : scope.row.original_send_money
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="配送金额"
            prop="send_money"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.order_empty
                  ? scope.row.order_empty.send_money
                  : scope.row.send_money
              }}
            </template></el-table-column
          >
          <!-- <el-table-column label="对账状态" prop="" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span :class="'account_status' + scope.row.account_status">{{
              account_status_list[scope.row.account_status]
            }}</span>
          </template>
        </el-table-column> -->
          <el-table-column
            label="管理操作"
            align="center"
            fixed="right"
            width="300"
          >
            <template slot-scope="scope" v-if="form.account_status != 2">
              <router-link
                :to="
                  '/financial/other/see/' +
                  scope.row.id +
                  '?type=' +
                  form.account_status
                "
              >
                <el-link type="success">查看</el-link></router-link
              >

              <router-link
                :to="
                  '/financial/other/account/' +
                  scope.row.id +
                  '?type=' +
                  form.account_status
                "
              >
                <el-link type="warning">对账</el-link></router-link
              >
              <el-link @click="print(scope.row)">打印</el-link>
              <el-link
                style="color: #118ab2"
                @click="handleExport(scope.row.id)"
                >导出</el-link
              >
              <el-link
                v-if="form.account_status == 1"
                @click="cancel(scope.row)"
                >作废</el-link
              >
            </template>
          </el-table-column>
          </el-table>
        </div>
      </template>
      <template v-slot:Page>
        <MainPagination
          :current-page="current.page"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          background
          @size-change="changeLimit"
          @current-change="changePage"
        />
      </template>
      <template v-slot:Dialog>
        <!-- 打印子组件 -->
        <order-print
          ref="printTemplate"
          v-show="false"
          id="printname"
        ></order-print>
      </template>
    </MainPage>
  </div>
</template>
<script>
import { mixins } from "@/mixins/index.js";
import {
  get_empty_index,
  batch_unbind_export,
  export_list,
  getCompletedBill,
  exportListEmpty,
  exportEmpty,
  batch_invalid,
} from "@/api/financial/finaicalOther";
import MainPage from "@/components/MainPage";
import dateOption from "@/options/dateOption";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";
import OrderPrint from "@/views/order/orderPrint.vue";
import { mapGetters } from "vuex";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
export default {
  mixins: [mixins],
  components: {
    MainPage,
    OrderPrint,
  },
  data() {
    return {
      dateOption,
      parseTime,
      exportMethod,
      createTime: [],
      sendTime: [],
      form: {
        send_start_time: "",
        send_end_time: "",
        create_start_time: "",
        create_end_time: "",
        uid: "",
        contact: "",
        order_sn: "",
        salesman_id: "",
        account_status: localStorage.getItem("accountStatus") || "0",
      },
      moredata: false,
      list: [],
      salesman: {},
      account_status_list: [],
      listLoading: false,
      exportLoading: false,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      selectArr: [],
    };
  },
  computed: {
    ...mapGetters({
      show_original_order_data: "show_original_order_data",
    }),
  },
  created() {
    this.getNumerical(240);
    this.get_empty_index();
  },
  beforeDestroy() {
    localStorage.removeItem("accountStatus");
  },
  methods: {
    //  表格双击跳转详情页面
    rowDblclick(row, column, event) {
      if(this.form.account_status != 2) this.$router.push('/financial/other/see/' + row.id + '?type=' + this.form.account_status)
    },
    startGetting() {
      this.getArticleList();
    },
    getSearchFor() {
      this.getArticleList();
    },
    //获取用户信息
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
    },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
    },
    getArticleList() {
      this.current.page = 1;
      this.get_empty_index();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.form.uid = "";
      this.$refs["changeUserInput"].name = "";
      this.createTime = [];
      this.sendTime = [];
      this.getArticleList();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.get_empty_index();
    },
    changePage(page) {
      this.current.page = page;
      this.get_empty_index();
    },
    get_empty_index() {
      console.log();
      let api = get_empty_index;
      if (this.form.account_status == 1 || this.form.account_status == 2) {
        api = getCompletedBill;
      }
      let data = Object.assign(this.list_form(), this.current);
      if (this.form.account_status != 0) {
        data.is_invalid = this.form.account_status == 2 ? 1 : 0;
      }
      this.listLoading = true;
      api(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.salesman = res.data.salesman;
          this.account_status_list = res.data.account_status_list;
          this.totalCount = res.data.list.total;
          this.list = res.data.list.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.send_start_time = this.sendTime ? this.sendTime[0] : "";
      form.send_end_time = this.sendTime ? this.sendTime[1] : "";
      form.create_start_time = this.createTime ? this.createTime[0] : "";
      form.create_end_time = this.createTime ? this.createTime[1] : "";
      return form;
    },
    handleExport(id) {
      let data = { id: id };
      let api = batch_unbind_export;
      let msg = "用户其他对账-未对账";
      if (this.form.account_status == 1) {
        api = exportEmpty;
        msg = "用户其他对账-已对账";
      }
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      api(data).then((res) => {
        this.exportMethod(res, msg, notify);
      });
    },
    //批量导出
    batchexport() {
      if (this.selectArr.length == 0) {
        this.$message.warning("请先勾选需要导出的项目");
        return;
      }
      this.exportLoading = true;
      let api = export_list;
      let msg = "用户其他对账-未对账";
      if (this.form.account_status == 1) {
        api = exportListEmpty;
        msg = "用户其他对账-已对账";
      }
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      api({ ids: this.selectArr.map((item) => item.id).join(",") })
        .then((res) => {
          this.exportMethod(res, msg, notify);
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id, uid: item.uid });
      });
    },
    // 打印
    print(row) {
      return new Promise((resolves, rejects) => {
        let id = row.id;
        let uid = row.uid;
        let continuous = row.continuous;
        this.$refs.printTemplate.$emit("demo", {
          id: id,
          uid: uid,
          type:
            this.form.account_status == 0
              ? "other_user_order"
              : "other_user_completed_order",
          continuous: continuous,
          cd: (res)=>{
            resolves();
          }
        });
      });
    },
    pldeliver() {
      if (this.selectArr.length != 0) {
        let length = this.selectArr.length;
        this.$confirm(
          `此操作将连续打印【${length}】张配送单,并且打印机需要设置为后进纸,是否继续?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            for (let index = 0; index < this.selectArr.length; index++) {
              const item = this.selectArr[index];

              await this.print({
                id: item.id,
                uid:item.uid,
                continuous: "continuous",
              });
            }
          })
          .catch(() => {});
      } else {
        this.$message.error("请勾选订单");
      }
    },
    cancel(row) {
      let data = {
        is_invalid: 1,
        id: row.id,
      };
      let query = this.packageApi(data);
      this.$confirm("此操作将作废该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          batch_invalid(query).then((res) => {
            if (res.errcode == 0) {
              this.get_empty_index();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    packageApi(data = {}) {
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      return query;
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/.el-tabs__header {
  width: 100%;
  margin-bottom: 0px;
}

.account_status0 {
  color: red;
}
.account_status1 {
  color: #03a98e;
}
.new_navbar_svg {
  vertical-align: bottom;
}

/deep/.mainor_form form {
  width: 100%;
  .el-form-item {
    margin-bottom: 10px;
    &.btn-bottom {
      margin-bottom: 1px;
    }
  }
}
</style>
